<?php
/**
 * aes 加密
 * @author pan.liang
 */
class nl_encrypt_aes
{
    private $securekey;
    private $iv;
    private $MCRYPT_RIJNDAEL;
    private $MCRYPT_MODE;

    function __construct($textkey='8888888888888888',$MCRYPT_RIJNDAEL=MCRYPT_RIJNDAEL_128,$MCRYPT_MODE=MCRYPT_MODE_ECB)
    {
        $this->securekey = $textkey;
        $this->iv = mcrypt_create_iv(32,MCRYPT_DEV_URANDOM);
        $this->MCRYPT_RIJNDAEL=$MCRYPT_RIJNDAEL;
        $this->MCRYPT_MODE = $MCRYPT_MODE;
    }


    private function UnPKCS7Padding($str)
    {
        $block=mcrypt_get_block_size($this->MCRYPT_RIJNDAEL,$this->MCRYPT_MODE);
        $char=substr($str,-1,1);
        $num=ord($char);
        if($num>8) {
            return $str;
        }
        $len=strlen($str);
        for($i=$len-1;$i>=$len-$num;$i--) {
            if(ord(substr($str,$i,1))!=$num) {
                return $str;
            }
        }
        $str=substr($str,0,-$num);
        return $str;
    }

    public function PKCS7Padding($str)
    {
        $block=mcrypt_get_block_size($this->MCRYPT_RIJNDAEL,$this->MCRYPT_MODE);
        $pad=$block-(strlen($str)%$block);
        if($pad<=$block)
        {
            $char=chr($pad);
            $str.=str_repeat($char,$pad);
        }
        return $str;
    }
    /**
     * 加密
     * @param unknown $input
     * @return string
     */
    public function encrypt($input)
    {
        $input = $this->PKCS7Padding($input);
        return urlencode(base64_encode(mcrypt_encrypt($this->MCRYPT_RIJNDAEL, $this->securekey, $input, $this->MCRYPT_MODE, $this->iv)));
    }

    /**
     * 解密
     * @param unknown $input
     * @return string
     */
    function decrypt($input)
    {
        return trim(mcrypt_decrypt($this->MCRYPT_RIJNDAEL, $this->securekey, base64_decode(urldecode($input)), $this->MCRYPT_MODE, $this->iv));
    }
}